import { t } from 'i18next'
import React, { useEffect, useRef, useState } from 'react'
import { IconMenu, Wrap } from './style'
import { Tab, Search, Trigger, TriggerInstance } from '@kedacom/react-next'
import { useBasicInfoStore } from '../basicInfo/store'
import { Menu } from './menu'
import { useDebounceEffect } from 'ahooks'
import { useUserStore } from './store'
import { useMeetingParamsStore } from '../meetingParams/store'
import { init as addMtInit, resetAllStore } from '@/components/AddMt/store.trans'
import { Confirm, confirmModal } from '@/components/Alert'
import { useUserAllStore } from './all/store'
import { SelectMtEntity } from '@/components/AddMt/translator'
import { addFromAddMt, searchUser } from './store.combine'
import { AllList } from './all'
import { OftenList } from './often'
import { InteractiveList } from './interactive'
import { vipSort2Users } from '../../store.combine'
import { useGlobalStore } from '@/store/global'

const TAB = [
	{
		value: 'all',
		label: t('全部终端'),
		width: 142,
	},
	{
		value: 'often',
		label: t('常用终端'),
		width: 142,
	},
	{
		value: 'interactive',
		label: t('互动终端'),
		width: 142,
	},
]

type ITab = 'all' | 'often' | 'interactive'

function useTab() {
	const [curTab, setCurTab] = useState<ITab>('all')
	const [tabs, setTabs] = useState([TAB[0], TAB[1]])

	const superMtNum = useBasicInfoStore((state) => state.superMtNum)
	const SWITCH = useGlobalStore((state) => state.SWITCH)
	useEffect(() => {
		setCurTab('all')
		if (superMtNum) {
			setTabs([TAB[0], TAB[2]])
		} else {
			if (!!SWITCH.showOftenMt) {
				setTabs([TAB[0], TAB[1]])
			} else {
				setTabs([])
			}
		}
	}, [superMtNum, SWITCH])

	return { tabs, tab: curTab, setCurTab }
}

function UserList() {
	const { tabs, tab, setCurTab } = useTab()

	const update = useUserStore((state) => state.update)

	const [searchVal, setSearchVal] = useState('')
	const handleSearch = (keyword: string) => {
		setSearchVal(keyword)
	}

	useDebounceEffect(
		() => {
			update({ keywords: searchVal })
			searchUser(searchVal)
		},
		[searchVal],
		{
			wait: 250,
		}
	)

	const handleAddMt = () => {
		//自建模式，等同之前的MCU
		const { meetingType, rate, simpleCascade, enableRtc, _H265, encryptionType } = useMeetingParamsStore.getState()
		const superMtNum = useBasicInfoStore.getState().superMtNum
		addMtInit({
			isOpen: true,
			showTrees: simpleCascade === 2 ? ['org', 'monitor'] : ['org', 'template', 'monitor'],
			maxRate: rate,
			selectedEntityMts: useUserAllStore.getState().tree.map((x) => ({
				account: x.mcc.account,
				accountType: x.mcc.account_type,
				name: x.mcc.name,
				protocol: x.mcc.protocol,
				bitrate: x.mcc.bitrate,
				portrait: x.mcc.portrait,
				e164: x.mcc.e164,
				oftenMt: +x.status.isOften as 0 | 1,
				interactiveMt: +x.status.isInteractive as 0 | 1,
			})),

			isSuperMeeting: superMtNum ? true : false,
			meetingType,
			isSupportRtc: meetingType === 2 || (enableRtc && !_H265 && encryptionType !== 3) ? true : false,

			curTemplateE164: useBasicInfoStore.getState().preAssignedMeetingNumber || '',
			onRemoveRoom: () => {
				Confirm(t('您确定要释放锁定和预定的会议室吗？'), function () {
					useBasicInfoStore.setState({ _isSearchRoomDialogShow: true })
				})
			},
			onSubmit: ({ selectedList, cascadeType, smcuMtid }) => {
				const mts = selectedList
				// 需要从用户列表中取出哪些是互动终端哪些书常用终端
				let interactiveUsers: Required<Omit<SelectMtEntity, 'meetingType'>>[] = [] //互助终端
				let oftenUsers: Required<Omit<SelectMtEntity, 'meetingType'>>[] = [] //常用终端

				mts.forEach((x) => {
					x.interactiveMt === 1 && interactiveUsers.push(x)
					x.oftenMt === 1 && oftenUsers.push(x)
				})

				const outerEmailMts = mts.filter((x) => x.accountType === 4) //外部邮箱号

				let type = 1
				//判断是否超出会议规模定义的大小，判断时移除外部邮箱
				//超大方判断互动终端
				let length = superMtNum
					? interactiveUsers.length - outerEmailMts.length
					: mts.length - outerEmailMts.length
				if (length > 190) {
					type = 2 //超过视频会议规模
				} else if (length > 80 && useMeetingParamsStore.getState().encryptedSM) {
					type = 3 //SM1加密且超过80方
				} else {
					type = 1 //没有超过会议规模
				}

				function addMt() {
					addFromAddMt({ users: mts, cascadeMap: cascadeType })
					resetAllStore()
					vipSort2Users()
				}

				if (type === 1) {
					addMt()
				} else if (type === 2) {
					//超过会议规模
					confirmModal({
						msg: t('添加的与会方数已超过当前会议规模，部分终端可能无法正常入会'),
						okText: t('继续邀请'),
						cancelText: t('返回修改'),
						onOk: () => {
							addMt()
						},
					})
				} else {
					confirmModal({
						msg: t('添加的与会方数已超过当前会议接入数上限，部分终端可能无法正常入会'),
						okText: t('继续邀请'),
						cancelText: t('返回修改'),
						onOk: () => {
							addMt()
						},
					})
				}
			},
		})
	}

	const TAB_COMPONENT = {
		all: <AllList />,
		often: <OftenList />,
		interactive: <InteractiveList />,
	}

	const menuRef = useRef<TriggerInstance>(null)

	return (
		<Wrap>
			<div className="list-title">
				<span>{t('与会方列表')}</span>
				<span id="add-mt" className="add-btn" onClick={handleAddMt}>
					+{t('添加与会方')}
				</span>
			</div>
			<Tab
				className={`${tabs.length > 1 ? '' : 'tabs'} list-tab`}
				type="button"
				data={tabs}
				value={tab}
				onChange={(e, v) => {
					setCurTab(v)
				}}
			/>
			<div className="list-actions">
				<Search
					className="list-search"
					maxLength={128}
					iconAlign="left"
					onChange={(e, v) => handleSearch(v)}
					onClear={() => handleSearch('')}
					value={searchVal}
					clearable
					placeholder={t('请输入关键字搜索')}
				/>
				<Trigger
					ref={menuRef}
					popup={
						<Menu
							tab={tab}
							onCancel={() => {
								menuRef.current?.close()
							}}
						/>
					}
					popupAlign={{ offset: [0, -30] }}
					preventOverflow
				>
					<IconMenu className="list-actions__menu" />
				</Trigger>
			</div>
			{TAB_COMPONENT[tab]}
		</Wrap>
	)
}
export default UserList
